/**
 * @file models/replay.js
 * @author
 */
import { routerRedux } from 'dva/router';
import api from '../api';
import moment from 'moment'


export default {
	namespace: 'replayList',
	state: {
		// filterValue:'1',
		// begindate:moment().format('YYYY-MM-DD'),
		// enddate:moment().format('YYYY-MM-DD'),
		begindate:'',
		enddate:'',
		keywords:''
	},
	subscriptions : {
		setup({dispatch, history}) {
			history.listen(({ pathname, query }) => {
				// 没有参数时，向后端请求数据，并且改变query
				if( pathname === '/tradeReplay/investReplay'){
					dispatch({type: 'whetherRequest',payload:query,pathname})
				}
			})
		}
	},
	effects : {

		* whetherRequest({
				payload,pathname
			}, { put,select}) {

				const {
					filterValue,
					begindate,
					enddate,
					keywords
				}=payload
				if(filterValue||begindate||enddate||keywords){
					if(!(begindate&&enddate)){
						yield put({
							type:'changeRouter',
							payload:{
								pathname
							}
						})
					}else{
						yield [
							put({
								type:'setState',
								payload
							}),
							put({
								type:'query',
								payload
							})
						]

					}
				}else{
					yield [
						put({
							type:'query',
							payload
						}),
						put({
							type:'setState',
							payload:{
								filterValue:'1'
							}
						})
					]

				}
		},
		* query({payload}, {call, put,select}){

			const response = yield call(api.replay.getReplayList, payload)

			yield put({type:'clearState'})

			yield put({
				type: 'querySuccess',
				payload:{
					begindate:payload.begindate||moment(response.data.total.dataDate).format('YYYY-MM-DD'),
					enddate:payload.enddate||moment(response.data.total.dataDate).format('YYYY-MM-DD'),
					...response.data
				}
			});
		},
		* changeRouter({payload}, {put}){
			yield put(routerRedux.push(payload))
		}

	},
	reducers : {
		setState(state, {payload}) {
			return {
				...state,
				...payload
			}
		},

		clearState(state) {
      return{
				...state,
				total:null,
				list:null
			}
    },
		querySuccess(state, {payload}) {
			return {
				...state,
				...payload
			}
		}

	}
};
